<?php
class lib_filter{
    
    private static $config;//搜索单元设置
    
    //每几个元素换行
    private static $brEvery;
    
    //过滤条件字符串
    private static $filter = array(
    	'find'=>array(),
    	'sort'=>array()
    );
    
	public function unitFactory($name,$unit){
    	$title = $unit[0];//show pre-word
    	if ('orderby' == $name)
    		return '按'.Form::select("filter[orderby]",$title,NULL,array('id'=>"filter_orderby"))
    		.Form::select("filter[orderdirect]",array('-1'=>'降序','1'=>'升序'),NULL,array('id'=>"filter_orderdirect")).'排序';
    	if (is_string($title)){
    		if (!isset($unit[1]))//'title'=>array('标题')
    			return $title.':'.Form::input("filter[$name]",false,array('id'=>"filter_$name"));
    			
    		elseif (is_array($unit[1]))//'select'=>array('请选择',array('no'=>'否','yes'='是'),'yes')
    			return $title.':'.Form::select("filter[$name]",$unit[1],isset($unit[2])?$unit[2]:NULL,array('id'=>"filter_$name"));
    			
    		elseif (is_int($unit[1]))//'addTime'=>array('添加时间',strtotime(date('Y-m')),time())
    			return $title.'从'.Form::input("filter[{$name}from]",date('Y-m-d',$unit[1]),array('id'=>"filter_{$name}from"))
    			.'到'.Form::input("filter[{$name}to]",date('Y-m-d',isset($unit[2])?$unit[2]:time()),array('id'=>"filter_{$name}to"));
    	}
    	return '';
    }
    
	public function filter($object){
    	foreach (self::$config as $name=>$unit){
    		$this->filterFactory($name, $unit,$object);
    	}
    	//var_dump(self::$filter);
    	$object = $object->find(self::$filter['find'])->sort(self::$filter['sort']);
    	return $object;
    }
    public function filterFactory($name,$unit,$object){
    	$filter = $_GET['filter'];
    	if ('orderby' == $name)
    		self::$filter['sort'][$filter['orderby']] = (int)$filter['orderdirect'];
    	if (is_string($unit[0])){
    		if (!isset($unit[1]))//'title'=>array('标题')
    			self::$filter['find'][$name] = new MongoRegex('/'.project::keyword_separate($filter[$name]).'/i');
    			
    		elseif (is_array($unit[1]))//'select'=>array('请选择',array('no'=>'否','yes'='是'),'yes')
    			self::$filter['find'][$name] = $filter[$name];
    			
    		elseif (is_int($unit[1]))//'addTime'=>array('添加时间',strtotime(date('Y-m')),time())
    			self::$filter['find'][$name] = array('$gte'=>strtotime($filter[$name.'from']),'$lt'=>strtotime($filter[$name.'to'].' +1 day'));
    	}
    	return $object;
    }
    
    public function filtering(){
    	return isset($_GET['filter']);
    }
    
	//主体初始化，传入控制器对象、过滤单元选项、每多少个单元换行
    public static function instance($config,$brEvery = 6){
    	self::$config = project::config('libconfig')->filter[$config];
        self::$brEvery = $brEvery;
        return new self;
    }
    
    public function render(){
    	$k = -1;
    	$v = '<form id="filterForm" method="get" action="">';
    	foreach (self::$config as $name=>$unit){
    		$v .= ++$k?($k % self::$brEvery ? '' : '<br />'):'';
            $v .= '<span style="margin:5px;white-space: nowrap;">';
            $v .= $this->unitFactory($name,$unit);
            $v .= '</span>';
    	}
    	//单元结尾
        $v .= Form::submit(false,'查询').Form::input(false,'重置',array('type'=>'reset')).'</form>';
        
        //单元保留前次搜素条件选择
        $v .= $this->script();
        
    	return $v;
    }
    
	//自动选择前次搜索条件
    public function script(){
    	if (!$this->filtering()) return '';
    	$v = '<script type="text/javascript">';
    	foreach (self::$config as $name=>$unit){
    		$v .= "\n".$this->scriptFactory($name,$unit);
    	}
        $v .= '</script>';
        return $v;
    }
    public function scriptFactory($name,$unit){
    	$filter = $_GET['filter'];
    	if ('orderby' == $name)
    		return "$('select#filter_orderby').val('{$filter['orderby']}');"
    		."$('select#filter_orderdirect').val('{$filter['orderdirect']}');";
    	if (is_string($unit[0])){
    		if (!isset($unit[1]))//'title'=>array('标题')
    			return "$('#filter_$name').val('{$filter[$name]}');";
    			
    		elseif (is_array($unit[1]))//'select'=>array('请选择',array('no'=>'否','yes'='是'),'yes')
    			return "$('select#filter_$name').val('{$filter[$name]}');";
    			
    		elseif (is_int($unit[1]))//'addTime'=>array('添加时间',strtotime(date('Y-m')),time())
    			return "$('#filter_{$name}from').val('{$filter[$name.'from']}');"
    			."$('#filter_{$name}to').val('{$filter[$name.'to']}');";
    	}
    	return '';
    }
}